package com.dmlll.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmlll.VO.HospitalCloseVO;
import com.dmlll.VO.HospitalPurchaseInputVO;
import com.dmlll.VO.PurchaseVO;
import com.dmlll.common.DataGridView;
import com.dmlll.common.ResultObj;
import com.dmlll.domain.*;
import com.dmlll.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dmLll
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/hospitalClose")
public class HospitalCloseController {
    @Autowired
    private HospitalCloseService hospitalCloseService;
    @Autowired
    private HospitalPurchaseInputService hospitalPurchaseInputService;
    @Autowired
    private PurchaseDrupDetailService purchaseDrupDetailService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private DrugMessageService drugMessageService;
    @Autowired
    private HospitalOutputDetailService hospitalOutputDetailService;
    @Autowired
    private HospitalCloseDetailService hospitalCloseDetailService;
    @Autowired
    private ProviderService providerService;

    /**
     * 查询本医院的结算单+模糊
     */
    @RequestMapping("loadAllClose")
    public DataGridView loadAllClose(HospitalCloseVO hospitalClose) {
        IPage<HospitalClose> page = new Page<>(hospitalClose.getPage(), hospitalClose.getLimit());
        QueryWrapper<HospitalClose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hospital_id", hospitalClose.getHospitalId())
                .like(StringUtils.isNotBlank(hospitalClose.getCloseNum()), "close_num", hospitalClose.getCloseNum())
                .like(StringUtils.isNotBlank(hospitalClose.getCloseName()), "close_name", hospitalClose.getCloseName())
                .eq(hospitalClose.getCloseState() != null && hospitalClose.getCloseState() > 0, "close_state", hospitalClose.getCloseState())
                .ge(hospitalClose.getStartTime() != null, "create_time", hospitalClose.getStartTime())
                .le(hospitalClose.getEndTime() != null, "create_time", hospitalClose.getEndTime());

        IPage<HospitalClose> iPage = hospitalCloseService.page(page, queryWrapper);
        return new DataGridView(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 添加结算单
     */
    @RequestMapping("add")
    public ResultObj add(HospitalClose hospitalClose, HttpSession session) {
        try {
            //填充采购单
            hospitalClose.setCloseNum(UUID.randomUUID().toString().substring(0, 7));
            hospitalClose.setCreateName(((User) session.getAttribute("user")).getLoginname());

            hospitalCloseService.save(hospitalClose);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_SUCCESS;
    }

    /**
     * 获得刚添加的结算单id
     *
     * @return
     */
    @RequestMapping("getNewHospitalCloseId")
    public Integer getNewHospitalCloseId() {
        return hospitalCloseService.getNewHospitalCloseId();
    }

    /**
     * 修改结算单
     * @param closeDetail
     * @return
     */
    @RequestMapping("update")
    public ResultObj update(HospitalClose close){
        try {
            hospitalCloseService.updateById(close);
        } catch (Exception e) {
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_SUCCESS;
    }
    /**
     * 通过id获得结算单
     *
     * @param id
     * @return
     */
    @RequestMapping("getHospitalCloseById")
    public HospitalClose getHospitalCloseById(Integer id) {
        return hospitalCloseService.getById(id);
    }

    /**
     * 以采购单详情为主
     *
     * @param purchase
     * @param hospitalCloseDetail
     * @param drugMessage
     * @param hospitalPurchaseInput
     * @return
     */
    @RequestMapping("getAvailableDrug")
    public DataGridView getAvailableDrug(Purchase purchase, HospitalCloseDetail hospitalCloseDetail,
                                         DrugMessage drugMessage, PurchaseDrupDetail purchaseDrupDetail,
                                         HospitalPurchaseInputVO hospitalPurchaseInput) {
        //当前医院的采购单，采购单中已入库
        //获取当前结算单的结算详情
        //1采购状态，所有已入库的药品
        QueryWrapper<Purchase> purchaseQueryWrapper = new QueryWrapper<>();
        purchaseQueryWrapper.eq("hospital_id", purchase.getHospitalId());//通过医院确定采购单范围
        //2添加条件，采购单编号、名称、开始采购时间、结束采购时间
        purchaseQueryWrapper.like(StringUtils.isNotBlank(purchase.getPurchaseNum()), "purchase_num", purchase.getPurchaseNum());
        purchaseQueryWrapper.like(StringUtils.isNotBlank(purchase.getPurchaseName()), "purchase_name", purchase.getPurchaseName());
        purchaseQueryWrapper.eq(purchase.getCreateTime() != null, "create_time", purchase.getCreateTime());
        purchaseQueryWrapper.eq(purchase.getOverTime() != null, "over_time", purchase.getOverTime());
        //1指定医院的采购单，2并符合特定的条件
        List<Purchase> purchaseList = purchaseService.list(purchaseQueryWrapper);
        QueryWrapper<PurchaseDrupDetail> ppdQueryWrapper = new QueryWrapper<>();
        ppdQueryWrapper.eq("purchase_state", 3);//通过采购详情确定已入库的
        //1指定采购单状态为已入库的
        List<PurchaseDrupDetail> ppdList = purchaseDrupDetailService.list(ppdQueryWrapper);
        //1给ppdList填充purchase
        ppdList.stream().forEach((PurchaseDrupDetail ppd) -> ppd.setPurchase(purchaseService.getById(ppd.getPurchaseId())));
        //1过滤不是该医院的已入库药品详情，已经是该医院已入库的采购详情
        List<PurchaseDrupDetail> resultList = ppdList.stream()
                .filter(ppd -> purchaseList.contains(ppd.getPurchase()) && ((purchaseDrupDetail.getProviderId() == null || purchaseDrupDetail.getProviderId() == 0) ? true : (purchaseDrupDetail.getProviderId().equals(ppd.getProviderId()))))
                .collect(Collectors.toList());
        //1获取结果中的药品信息,2筛选药品
        List<PurchaseDrupDetail> resultList2 = resultList.stream().filter((res) -> {
            //筛选药品
            res.setDrugMessage(drugMessageService.getById(res.getDrugMessageId()));
            DrugMessage dm = res.getDrugMessage();
            if (drugMessage.getSerialNumber() != "" && drugMessage.getSerialNumber() != null) {
                if (!dm.getSerialNumber().contains(drugMessage.getSerialNumber())) {
                    return false;
                }
            }
            if (drugMessage.getCommonName() != "" && drugMessage.getCommonName() != null) {
                if (!dm.getCommonName().contains(drugMessage.getCommonName())) {
                    return false;
                }
            }
            if (drugMessage.getDosageForm() != "" && drugMessage.getDosageForm() != null) {
                if (!dm.getDosageForm().contains(drugMessage.getDosageForm())) {
                    return false;
                }
            }
            if (drugMessage.getSize() != "" && drugMessage.getSize() != null) {
                if (!dm.getSize().contains(drugMessage.getSize())) {
                    return false;
                }
            }
            if (drugMessage.getUnit() != "" && drugMessage.getUnit() != null) {
                if (!dm.getUnit().contains(drugMessage.getUnit())) {
                    return false;
                }
            }
            if (drugMessage.getFactor() != null) {
                if (!dm.getFactor().equals(drugMessage.getFactor())) {
                    return false;
                }
            }
            if (drugMessage.getProductionName() != "" && drugMessage.getProductionName() != null) {
                if (!dm.getProductionName().contains(drugMessage.getProductionName())) {
                    return false;
                }
            }
            if (drugMessage.getCommodityName() != "" && drugMessage.getCommodityName() != null) {
                if (!dm.getCommodityName().contains(drugMessage.getCommodityName())) {
                    return false;
                }
            }
            if (drugMessage.getQuality() != null && drugMessage.getQuality() != 0) {
                if (!dm.getQuality().equals(drugMessage.getQuality())) {
                    return false;
                }
            }
            if (drugMessage.getDrugCategory() != null && drugMessage.getDrugCategory() != 0) {
                if (!dm.getDrugCategory().equals(drugMessage.getDrugCategory())) {
                    return false;
                }
            }
            if (drugMessage.getApprovalNumber() != "" && drugMessage.getApprovalNumber() != null) {
                if(dm.getApprovalNumber()==null)
                    return false;
                if (!dm.getApprovalNumber().contains(drugMessage.getApprovalNumber())) {
                    return false;
                }
            }
            return true;
        }).collect(Collectors.toList());
        //1获得结果中的结算信息，2筛选结算
        List<PurchaseDrupDetail> resultList3 = resultList2.stream().filter((res) -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("purchase_id", res.getPurchaseId());
            queryWrapper.eq("drug_message_id", res.getDrugMessageId());
            res.setClose(hospitalCloseDetailService.getOne(queryWrapper));
            if (res.getClose() == null)
                return false;
            if (hospitalCloseDetail.getCloseState() != null && hospitalCloseDetail.getCloseState() != 0) {
                if (res.getClose().getCloseState() == null)
                    return false;
                if (!hospitalCloseDetail.getCloseState().equals(res.getClose().getCloseState())) {
                    return false;
                }
            }
            return true;
        }).collect(Collectors.toList());
        //1获得结果中的入库信息，2筛选入库
        List<PurchaseDrupDetail> resultList4 = resultList3.stream().filter(res -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("purchase_id", res.getPurchaseId());
            queryWrapper.eq("drug_message_id", res.getDrugMessageId());
            res.setInput(hospitalPurchaseInputService.getOne(queryWrapper));
            HospitalPurchaseInput input = res.getInput();
            if (hospitalPurchaseInput.getStartTime() != null) {
                if (input == null || input.getInputTime().getTime() < hospitalPurchaseInput.getStartTime().getTime()) {
                    return false;
                }
            }
            if (hospitalPurchaseInput.getEndTime() != null) {
                if (input == null || input.getInputTime().getTime() > hospitalPurchaseInput.getEndTime().getTime()) {
                    return false;
                }
            }
            if (hospitalPurchaseInput.getInputForm() != null && hospitalPurchaseInput.getInputForm() != "") {
                if (input == null)
                    return false;
                if (!input.getInputForm().contains(hospitalPurchaseInput.getInputForm()) &&
                        !input.getInvoiceNum().contains(hospitalPurchaseInput.getInputForm()))
                    return false;
            }
            return true;
        }).collect(Collectors.toList());
        resultList4.forEach(res -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("purchase_id", res.getPurchaseId());
            queryWrapper.eq("drug_message_id", res.getDrugMessageId());
            res.setOutput(hospitalOutputDetailService.getOne(queryWrapper));
            res.setProvider(providerService.getById(res.getProviderId()));
        });
        return new DataGridView(resultList4);
    }

    /**
     * 已入库未结算
     * @param purchase
     * @param drugMessageIds
     * @param purchaseIds
     * @param drugMessage
     * @param purchaseDrupDetail
     * @param hospitalPurchaseInput
     * @return
     */
    @RequestMapping("getAvaCatalog")
    public DataGridView getAvaCatalog(Purchase purchase,Integer[] drugMessageIds,Integer[] purchaseIds,
                                      DrugMessage drugMessage, PurchaseDrupDetail purchaseDrupDetail,
                                      HospitalPurchaseInputVO hospitalPurchaseInput){
        IPage<PurchaseDrupDetail> iPage = new Page<>(hospitalPurchaseInput.getPage(),hospitalPurchaseInput.getLimit());
        IPage<PurchaseDrupDetail> pddList = hospitalCloseDetailService.getAvaCatalog(iPage,purchase,drugMessage,purchaseDrupDetail,hospitalPurchaseInput,drugMessageIds,purchaseIds);
        for (PurchaseDrupDetail pdd:pddList.getRecords()) {
            pdd.setProvider(providerService.getById(pdd.getProviderId()));
            pdd.setPurchase(purchaseService.getById(pdd.getPurchaseId()));
            pdd.setDrugMessage(drugMessageService.getById(pdd.getDrugMessageId()));
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("drug_message_id",pdd.getDrugMessageId());
            queryWrapper.eq("purchase_id",pdd.getPurchaseId());
            pdd.setInput(hospitalPurchaseInputService.getOne(queryWrapper));
            pdd.setOutput(hospitalOutputDetailService.getOne(queryWrapper));
//            pdd.setClose(hospitalCloseDetailService.getOne(queryWrapper));
        }
        return new DataGridView(pddList.getTotal(),pddList.getRecords());
    }
}
